package com.yeyks.commonReference.service.vip.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.base.PageResult;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.dto.MemberCardEnableOrderDTO;
import com.yeyks.common.dto.member.MemberCardTsOrderDTO;
import com.yeyks.common.em.pay.PayTypeEnum;
import com.yeyks.common.em.vip.MemberCardEnableOrderStatusEnum;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.MemberCardEnableOrderParam;
import com.yeyks.common.param.member.MemberCardTsOrderQueryParam;
import com.yeyks.common.result.member.MemberCardTsOrderResult;
import com.yeyks.common.result.order.MemberCardEnableOrderDownLoadResult;
import com.yeyks.common.utils.DateUtils;
import com.yeyks.common.utils.FormatUtils;
import com.yeyks.common.utils.IdWorkerUtil;
import com.yeyks.common.utils.ObjectConvertUtil;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.consumer.MemberCardService;
import com.yeyks.commonReference.service.vip.MemberCardEnableOrderService;
import com.yeyks.commonReference.service.vip.MemberCardGiftInfoService;
import com.yeyks.consumer.dal.domain.MemberCard;
import com.yeyks.consumer.dal.domain.UserInfo;
import com.yeyks.consumer.service.UserInfoService;
import com.yeyks.consumer.service.UserInviteRelationService;
import com.yeyks.vip.dal.dao.MemberCardEnableOrderMapper;
import com.yeyks.vip.dal.domain.MemberCardEnableOrder;
import com.yeyks.vip.dal.domain.MemberCardGiftInfo;
import com.yeyks.vip.dal.domain.MemberCardSellRelation;
import com.yeyks.vip.param.MemberCardEnableOrderPlaceAnOrderParam;
import com.yeyks.vip.param.MiniCardWithdrawalOrderCheckParam;
import com.yeyks.vip.result.MiniCardWithdrawalOrderCheckResult;
import com.yeyks.vip.service.MemberCardSellRelationService;
import com.yeyks.vip.vo.MemberCardEnableOrderPlaceAnOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;


/**
 * <p>
 * vip卡支付订单表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-08-07
 */
@Service
public class MemberCardEnableOrderServiceImpl extends ServiceImpl<MemberCardEnableOrderMapper, MemberCardEnableOrder> implements MemberCardEnableOrderService {

    @Autowired
    private MemberCardService memberCardService;
    @Autowired
    private MemberCardGiftInfoService memberCardGiftInfoService;
    @Autowired
    private MemberCardSellRelationService memberCardSellRelationService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private UserInviteRelationService userInviteRelationService;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * v3.6
     * 下单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberCardEnableOrderPlaceAnOrderVo placeAnOrder(@Validated MemberCardEnableOrderPlaceAnOrderParam param) {
        //参数校验
        switch (param.getCardType()) {
            case 1:
                if (StrUtil.isBlank(param.getAddress())) {
                    throw new ServiceException("地址不能为空");
                }
                break;
            case 2:
                if (StrUtil.isBlank(param.getPhoneSell())) {
                    throw new ServiceException("关联人不能为空");
                }
                break;
        }
        //判断卡是否可用
        MemberCard memberCard = memberCardService.getOne(new QueryWrapper<MemberCard>()
                .eq(MemberCard.CARD_NO, param.getCardNo())
                .eq(MemberCard.ENABLE, 0)
                .eq(MemberCard.STATUS, 1)
                .eq(MemberCard.CARD_TYPE, param.getCardType())
                .last("limit 1")
        );
        if (null == memberCard) {
            throw new ServiceException("会员卡不存在或已经可激活");
        }
        //生成订单号
        String orderNo = "vipEnable" + IdWorkerUtil.nextStrId();
        //添加订单
        MemberCardEnableOrder memberCardEnableOrder = new MemberCardEnableOrder();
        memberCardEnableOrder.setOrderNo(orderNo);
        memberCardEnableOrder.setCardNo(param.getCardNo());
        memberCardEnableOrder.setStatus(MemberCardEnableOrderStatusEnum.pay_pre.value());
        memberCardEnableOrder.setCreateTime(new Date());
        memberCardEnableOrder.setCardType(param.getCardType());
        if (Objects.isNull(memberCard.getSalePrice()) || CompareUtil.compare(memberCard.getSalePrice(), 0) <= 0) {
            throw new ServiceException("会员卡异常");
        }
        memberCardEnableOrder.setPayValue(memberCard.getSalePrice());
        boolean save = save(memberCardEnableOrder);
        if (!save) {
            throw new ServiceException("订单生成失败");
        }
        switch (param.getCardType()) {
            case 1:
                //存储用户信息
                MemberCardGiftInfo memberCardGiftInfo = new MemberCardGiftInfo();
                memberCardGiftInfo.setOrderNo(orderNo);
                memberCardGiftInfo.setName(param.getName());
                memberCardGiftInfo.setPhone(param.getPhone());
                memberCardGiftInfo.setAddress(param.getAddress());
                memberCardGiftInfo.setStatus(0);
                memberCardGiftInfo.setCreatedTime(new Date());
                save = memberCardGiftInfoService.save(memberCardGiftInfo);
                if (!save) {
                    throw new ServiceException("用户信息存储失败");
                }
                break;
            case 2:
                MemberCardSellRelation memberCardSellRelation = new MemberCardSellRelation();
                memberCardSellRelation.setOrderNo(orderNo);
                memberCardSellRelation.setCardNo(param.getCardNo());
                memberCardSellRelation.setName(param.getName());
                memberCardSellRelation.setPhone(param.getPhone());
                memberCardSellRelation.setPhoneSell(param.getPhoneSell());
                memberCardSellRelation.setStatus(1);
                save = memberCardSellRelationService.save(memberCardSellRelation);
                if (!save) {
                    throw new ServiceException("用户信息存储失败");
                }
                break;
        }
        return new MemberCardEnableOrderPlaceAnOrderVo().setOrderNo(orderNo);
    }

    @Override
    public AjaxResponseBody selectPageList(MemberCardEnableOrderParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MemberCardEnableOrderDTO> pageList = this.baseMapper.selectPageByParam(param);
        PageInfo<MemberCardEnableOrderDTO> pageInfo = new PageInfo<>(pageList);
        return AjaxResponseBody.success(pageInfo);
    }

    /**
     * 订单列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<MemberCardEnableOrderDTO> myList(MemberCardEnableOrderParam param) {
        Map<String, Object> paramMap = getParamMap(param);
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MemberCardEnableOrderDTO> memberCardEnableOrderDTOS = baseMapper.selectMyList(paramMap);
        return PageResult.getPageResult(memberCardEnableOrderDTOS);
    }

    /**
     * 订单导出
     *
     * @param param
     * @return
     */
    @Override
    public List<MemberCardEnableOrderDownLoadResult> download(MemberCardEnableOrderParam param) {
        Map<String, Object> paramMap = getParamMap(param);
        List<MemberCardEnableOrderDTO> memberCardEnableOrderDTOS = baseMapper.selectMyList(paramMap);
        List<MemberCardEnableOrderDownLoadResult> results = Lists.newArrayList();
        for (MemberCardEnableOrderDTO memberCardEnableOrderDTO : memberCardEnableOrderDTOS) {
            MemberCardEnableOrderDownLoadResult result = BeanUtil.toBean(memberCardEnableOrderDTO, MemberCardEnableOrderDownLoadResult.class);
            result.setCreateTime(DateUtil.format(memberCardEnableOrderDTO.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
            if (null != memberCardEnableOrderDTO.getPaymentMethod()) {
                result.setPaymentMethod(PayTypeEnum.getDesc(memberCardEnableOrderDTO.getPaymentMethod()));
            }
            result.setStatus(MemberCardEnableOrder.Status.getDesc(memberCardEnableOrderDTO.getStatus()));
            result.setPayValue(FormatUtils.fenToYuan(memberCardEnableOrderDTO.getPayValue()));
            results.add(result);
        }
        return results;
    }

    /**
     * 上次提现到这次提现中订单
     *
     * @param loginUser
     * @param param
     * @return
     */
    @Override
    public PageResult<MiniCardWithdrawalOrderCheckResult> periodOrder(AccountInfo loginUser, MiniCardWithdrawalOrderCheckParam param) {
        Arguments.isFalse(AccountType.Administrator == loginUser.getType(), "你无权访问");
        Map<String, Object> paramMap = Maps.newHashMap();
        if (ObjectUtil.isNotNull(param.getStartTime())) {
            paramMap.put("startTime", new Date(param.getStartTime()));
        }
        paramMap.put("endTime", new Date(param.getEndTime()));
        paramMap.put("status", MemberCardEnableOrder.Status.success.value());
        paramMap.put("accountId", param.getAccountId());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MiniCardWithdrawalOrderCheckResult> memberCardEnableOrderDTOS = baseMapper.periodOrder(paramMap);
        return PageResult.getPageResult(memberCardEnableOrderDTOS);
    }

    @Override
    public PageResult<MemberCardTsOrderDTO> queryTsPage(MemberCardTsOrderQueryParam param) {

        Map<String, Object> map = ObjectConvertUtil.objectToMap(param);
        Date startDate = DateUtils.yyyyMMddToDate(param.getCreateTime());
        assert map != null;
        map.put("startTime", startDate);
        if (null != startDate) {
            Date endDate = DateUtils.afterDaysToDate(startDate, 1L);
            map.put("endTime", endDate);
        }
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<MemberCardTsOrderDTO> queryList = baseMapper.queryTsPage(map);
        //插入邀请人手机号信息
        if(!CollUtil.isEmpty(queryList)){
            queryList.forEach(memberCardTsOrderDTO -> {
                if(memberCardTsOrderDTO.getUserId() != null){
//                    String phone = userInviteRelationService.getParentPhone(memberCardTsOrderDTO.getUserId());
//                    if(Arguments.strNotNull(phone)){
//                        memberCardTsOrderDTO.setParentPhone(phone);
//                    }
//
                    //如果没有收货人手机号就直接存入用户手机号
                    if(Arguments.strIsNull(memberCardTsOrderDTO.getReceivePhone())){
                        memberCardTsOrderDTO.setReceivePhone(memberCardTsOrderDTO.getUserPhone());
                    }
                }
                if(memberCardTsOrderDTO.getInviteCode() != null) {
                    //上级手机号
                    UserInfo parent  = userInfoService.getByInviteCode(memberCardTsOrderDTO.getInviteCode()) ;
                    if(null!=parent&&Arguments.strNotNull(parent.getPhone()))
                    {
                        memberCardTsOrderDTO.setParentPhone(parent.getPhone());
                    }
                }
            });
        }
        return PageResult.getPageResult(queryList);
    }

    @Override
    public List<MemberCardTsOrderResult> tsDownload(MemberCardTsOrderQueryParam param) {
        Map<String, Object> map = ObjectConvertUtil.objectToMap(param);
        Date startDate = DateUtils.yyyyMMddToDate(param.getCreateTime());
        assert map != null;
        map.put("startTime", startDate);
        if (null != startDate) {
            Date endDate = DateUtils.afterDaysToDate(startDate, 1L);
            map.put("endTime", endDate);
        }
        List<MemberCardTsOrderDTO> queryList = baseMapper.queryTsPage(map);
        //插入邀请人手机号信息
        if(!CollUtil.isEmpty(queryList)){
            queryList.forEach(memberCardTsOrderDTO -> {
                if(memberCardTsOrderDTO.getUserId() != null){
                    //如果没有收货人手机号就直接存入用户手机号
                    if(Arguments.strIsNull(memberCardTsOrderDTO.getReceivePhone())){
                        memberCardTsOrderDTO.setReceivePhone(memberCardTsOrderDTO.getUserPhone());
                    }
                }

                if(memberCardTsOrderDTO.getInviteCode() != null) {
                    //上级手机号
                    UserInfo parent  = userInfoService.getByInviteCode(memberCardTsOrderDTO.getInviteCode()) ;
                    if(null!=parent&&Arguments.strNotNull(parent.getPhone()))
                    {
                        memberCardTsOrderDTO.setParentPhone(parent.getPhone());
                    }
                }
            });
        }
        return ObjectConvertUtil.convertList(queryList, MemberCardTsOrderResult.class);
    }

    private Map<String, Object> getParamMap(MemberCardEnableOrderParam param) {
        Map<String, Object> paramMap = Maps.newHashMap();
        if (ObjectUtil.isNotNull(param.getStartTime()) && ObjectUtil.isNotNull(param.getEndTime())) {
            paramMap.put("startTime", new Date(param.getStartTime()));
            paramMap.put("endTime", new Date(param.getEndTime()));
        }
        if (StrUtil.isNotBlank(param.getOrderNo())) {
            paramMap.put("orderNo", param.getOrderNo());
        }
        if (StrUtil.isNotBlank(param.getPhone())) {
            paramMap.put("phone", param.getPhone());
        }
        if (ObjectUtil.isNotNull(param.getStatus())) {
            paramMap.put("status", param.getStatus());
        }
        return paramMap;
    }

}
